<template>
  <a-modal v-model:visible="msgBox.visible" @ok="msgBox.handleOk" @cancel="msgBox.handleCancel">
    <template #title>
      {{ msgBox.title }}
    </template>
    <div>{{ msgBox.msg }}
    </div>
  </a-modal>
  <a-table :columns="columns" :data="accountList" :row-selection="selectModel" summary>
    <template #username="{ rowIndex }">
      <a-input v-model="accountList[rowIndex].username" v-if="lineEnable[rowIndex] && !!accountList[rowIndex].add"
               :max-length="16" allow-clear
               show-word-limit/>
      <span v-else>{{ accountList[rowIndex].username }}</span>
    </template>

    <template #name-filter="{ filterValue, setFilterValue, handleFilterConfirm, handleFilterReset}">
      <div class="custom-filter">
        <a-space direction="vertical">
          <a-input :model-value="filterValue[0]" @input="(value)=>setFilterValue([value])"/>
          <div class="custom-filter-footer">
            <a-button @click="handleFilterConfirm">确定</a-button>
            <a-button @click="handleFilterReset">重置</a-button>
          </div>
        </a-space>
      </div>
    </template>
    <template #password="{ rowIndex }">
      <a-input-password v-model="accountList[rowIndex].password" v-if="lineEnable[rowIndex]" :max-length="16"
                        allow-clear show-word-limit/>
      <span v-else>******</span>
    </template>
    <template #mdAlgorithm="{ rowIndex }">
      <a-select placeholder="Please select ..." :model-value="mdAlgorithms[accountList[rowIndex].mdAlgorithm]"
                v-if="lineEnable[rowIndex]" @change="value => accountList[rowIndex].mdAlgorithm = value">
        <a-option v-for="(displayName ,name) in mdAlgorithms" :key="name" :value="name">{{ displayName }}</a-option>

      </a-select>
      <span v-else>{{ accountList[rowIndex].mdAlgorithm }}</span>
    </template>
    <template #optional="{ rowIndex }">
      <a-space>
        <a-button v-if="lineEnable[rowIndex]" @click="save(rowIndex)" status="normal">
          <template #icon>
            <icon-save/>
          </template>
        </a-button>
        <a-button v-if="lineEnable[rowIndex]" @click="cancelEdit(rowIndex)" status="success" title="取消编辑">
          <template #icon>
            <icon-close-circle/>
          </template>
        </a-button>
        <a-button @click="lineEnable[rowIndex] = true" v-else status="warning">
          <template #icon>
            <icon-edit/>
          </template>
        </a-button>
        <a-button status="danger" @click="deleteAccount(accountList[rowIndex].username, rowIndex)">
          <template #icon>
            <icon-delete/>
          </template>
        </a-button>
      </a-space>
    </template>
    <template #account_status="{ record }">
      <a-switch
          checked-color="rgb(var(--blue-4)"
          unchecked-color="rgb(var(--gray-4)" :model-value="record.status" @change="changeAccountStatus(record)"/>
    </template>
    <template #summary-cell="{ column }">
      <span v-if="column.dataIndex === 'username'">
       <a-button size="small" @click="newLine">
       <template #icon>
       <icon-plus/>
      </template></a-button>
      </span>

    </template>
  </a-table>


</template>
<script>
import {doExchangeByCachePk} from "@/js/dh"
import {Message} from "@arco-design/web-vue";
import {h} from "vue";
import {IconSearch, IconEdit, IconDelete, IconPlus, IconSave, IconCloseCircle} from "@arco-design/web-vue/es/icon";
import {get ,postPK} from "@/js/axios_util";

const voidFunction = () => {
};
export default {
  name: 'dev_account',
  components: {
    IconEdit, IconDelete, IconPlus, IconSave, IconCloseCircle
  },
  data() {
    return {
      title: "dev_account",
      lineEnable: [],
      mdAlgorithms: {},
      msgBox: {
        visible: false,
        title: "Title",
        msg: "none",
      },
      columns: [
        {
          title: '用户名',
          dataIndex: 'username',
          slotName: 'username',
          filterable: {
            filter: (value, record) => record.name.includes(value),
            slotName: 'name-filter',
            icon: () => h(IconSearch)
          }
        },
        {
          title: '状态',
          dataIndex: 'status',
          slotName: 'account_status'
        },
        {
          title: '密码',
          dataIndex: 'password',
          slotName: 'password'
        },
        {
          title: '摘要算法',
          dataIndex: 'mdAlgorithm',
          slotName: 'mdAlgorithm'
        },
        {
          title: '操作',
          slotName: 'optional'
        }

      ],
      selectModel: {
        type: 'checkbox',
        showCheckedAll: true
      },
      accountList: []
      , currentSaveLine: -1
    }
  }, methods: {
    onListResult(response) {
      let data = response.data;
      if (!data) {
        return;
      }
      this.accountList = data;
    },
    cancelEdit(rowIndex) {
      this.showMsgBox("是否取消编辑", "编辑的数据将不会保存", () => {
        let url = "/devAccount/getUserByName"
        get(url + '?username=' + this.accountList[rowIndex].username
            , (response) => {
              this.accountList[rowIndex] = response.data;
              this.lineEnable[rowIndex] = false;
            })

      })
    },
    showMsgBox(title, msg, ok, cancel) {
      if (msg === null) {
        return
      }
      this.msgBox.handleOk = ok ? ok : voidFunction;
      this.msgBox.handleCancel = cancel ? cancel : voidFunction;
      this.msgBox.title = title ? title : "Tip";
      this.msgBox.msg = msg;
      this.msgBox.visible = true;
    },
    listUser() {
      get('/devAccount/list', this.onListResult);

    }, changeAccountStatus(record) {
      let url = '/devAccount/changeStatus';
      let newStatus = !record.status;
     get(url + '?username=' + record.username + '&status=' + newStatus, (respone) => {
        if (respone.data) {
          record.status = newStatus;
        }
      })
    },
    deleteAccount(username) {
      this.showMsgBox("确定", "是否删除?", () => {
        let url = '/devAccount/delete';
        if (process.env.NODE_ENV === 'development') {
          url = window.dev.httpUrlBase + url;
        }
        get(url + '?username=' + username, (respone) => {
          if (!respone.data) {
            Message.error({content: '操作失败', showIcon: true})
            return
          }
          this.listUser();
        })
      })
    },
    newLine() {
      this.accountList.push({
        add: true,
        status: true,
        mdAlgorithm: 'MD5',
      })
      this.lineEnable[this.accountList.length - 1] = true;
    },
    save(rowIndex) {
      let account = this.accountList[rowIndex];
      if (account.username === null || account.username === "") {
        Message.error({content: "用户名不能为空", showIcon: true})
        return
      }
      if (account.add && account.password === null || account.password === "") {
        Message.error({content: "新增用户密码不能为空", showIcon: true})
        return
      }
      this.currentSaveLine = rowIndex;
      doExchangeByCachePk((keyAgreeResult, aesEncode) => {
        const currentSaveLine = this.currentSaveLine;
        if (!this.currentSaveLine < 0) {
          return
        }
        let account = this.accountList[currentSaveLine];

        const accountDto = {
          username: account.username,
          mdAlgorithm: account.mdAlgorithm,
          status: account.status,

        }

        if (account.password && account.password.length > 0) {
          accountDto.password = aesEncode(account.password, keyAgreeResult.secret)
        }
        postPK('/devAccount/saveAccount', accountDto, keyAgreeResult, response1 => {
          let msg = response1.data ? "保存成功" : "操作失败"
          this.lineEnable[currentSaveLine] = false;
          this.accountList[currentSaveLine].add = false;
          Message.info({content: msg, showIcon: true})
        }, (response) => {
          keyAgreeResult.secret.fill(0);
          this.accountList[currentSaveLine].password = "";
          console.log(response.response.status);
        })

      })
    }
  }
  ,
  created() {
    get("/devAccount/getMdAlgorithms" ,(response) => this.mdAlgorithms = response.data )
    this.listUser()
  }

}
</script>
<style>
.switch {
  color: #18c212;
}
</style>